package com.geeksx.trainer.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.geeksx.trainer.common.exception.BusinessException;
import com.geeksx.trainer.entity.User;
import com.geeksx.trainer.entity.request.RegisterRequest;
import com.geeksx.trainer.entity.request.UserProfileRequest;
import com.geeksx.trainer.entity.vo.UserVO;
import com.geeksx.trainer.mapper.UserMapper;
import com.geeksx.trainer.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.validation.BindException;

/**
 * Copyright (C), 2025, 北京同创永益科技发展有限公司
 *
 * @Classname UserServiceImpl
 * @Description TODO
 * @Date 2025/8/26 14:54
 * @Created by zhengkaixuan
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public boolean register(RegisterRequest request) {
        // 检查用户名是否存在
        User existUser = userMapper.existsByUsername(request.getUsername());
        if (existUser != null){
            throw new BusinessException("用户名已存在");
        }
        User user = new User();
        user.setUsername(request.getUsername());
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        userMapper.insert(user);
        return true;
    }

    @Override
    public User login(User  user) {
        QueryWrapper<User> query = new QueryWrapper<>();
        query.eq("username", user.getUsername())
                .eq("password", user.getPassword());
        return userMapper.selectOne(query);
    }

    @Override
    public User getById(Long id) {
        return userMapper.selectById(id);
    }

    @Override
    public UserVO getByLoginName(String username) {
        QueryWrapper<User> query = new QueryWrapper<>();
        query.eq("username", username);
        User user = userMapper.selectOne(query);
        if (user != null) {
            UserVO userVO = new UserVO();
            BeanUtils.copyProperties(user, userVO);
            return userVO;
        } else {
            throw new BusinessException("用户不存在");
        }
    }

    @Override
    public void updateProfile(UserProfileRequest request) {
        User user = new User();
        user.setId(request.getId());
        user.setGender(request.getGender());
        user.setEmail(request.getEmail());
        userMapper.updateById(user);
    }

    @Override
    public void updateUserAvatar(Long userId, String avatarPath) {
        User user = new User();
        user.setId(userId);
        user.setAvatar(avatarPath);
        userMapper.updateById(user);
    }
}
